﻿using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System.Web;
using Microsoft.AspNetCore.Http;
using System.Net;
using System.IO;
using System.Threading.Tasks;
using Microsoft.Extensions.FileProviders;
using System;

namespace 综合同步.Controllers
{
    [ApiController]
    [Route("[controller]/[action]")]
    public class VideoController : ControllerBase
    {
        private readonly ILogger<VideoController> _logger;

        public VideoController(ILogger<VideoController> logger)
        {
            _logger = logger;
        }
        [HttpGet]
        public Task GetFile(string file)
        {
            long size = 1024*1024,from=0,to=0;
            file = file.Replace("StaticFiles/",LocalServer.GetConfigValue<string>("DataPath"));
            Response.ContentType = "video/mp4";
            Response.Headers["Cache-Control"] = "no-cache";
            FileInfo fileInfo = new FileInfo(file);
            string rangeHeader = Request.Headers["Range"];
            if(!string.IsNullOrEmpty(rangeHeader))
            {
                Response.StatusCode = (int)HttpStatusCode.PartialContent;
                string[] szRange = rangeHeader.Replace("bytes=", string.Empty).Split(new char[]{',','-'});
                from = long.TryParse(szRange[0], out from)?from:0;
                if(szRange.Length>1 && !string.IsNullOrEmpty(szRange[1])){
                    to = long.TryParse(szRange[1], out to)?to:0;
                }
                if(from+size<fileInfo.Length){
                    size = to>0?to:size;
                    Response.ContentLength = size;
                    Response.Headers["Content-Range"] = "bytes "+from+"-"+(size+from-1)+"/"+fileInfo.Length;
                    return Response.SendFileAsync(file,from,size);
                }
                else{
                    Response.ContentLength = fileInfo.Length-from;
                    Response.Headers["Content-Range"] = "bytes "+from+"-"+(fileInfo.Length-1)+"/"+fileInfo.Length;
                    return Response.SendFileAsync(file,from,fileInfo.Length-from);
                }
            }
            else
            {
                Response.StatusCode = (int)HttpStatusCode.OK;
                return Response.SendFileAsync(file,0,fileInfo.Length);
            }
        }
    }
}
